#!/bin/bash

# 获取acs_server.jar进程的所有PID
PIDS=$(ps -ef | grep -v grep | grep acs_server.jar | awk '{print $2}')

# 检查是否找到了进程
if [ -z "$PIDS" ]; then
    echo "未找到acs_server.jar进程"
    exit 0
fi

echo "找到acs_server.jar进程PID: $PIDS"

# 获取ss -antlp中所有java进程的PID
JAVA_PIDS=$(ss -antlp | grep java | awk -F'[=,]' '{print $2}' | sort -u)

echo "ss -antlp中的java进程PID: $JAVA_PIDS"

# 调试：显示原始的ss输出
echo "=== 调试：ss -antlp | grep java 原始输出 ==="
ss -antlp | grep java
echo "=== 调试结束 ==="

# 将PID转换为数组进行比较
PIDS_ARRAY=($PIDS)
JAVA_PIDS_ARRAY=($JAVA_PIDS)

echo "PIDS数组内容: ${PIDS_ARRAY[*]}"
echo "JAVA_PIDS数组内容: ${JAVA_PIDS_ARRAY[*]}"

# 检查每个acs_server.jar的PID是否在ss的java进程中
PIDS_TO_KILL=()

for pid in "${PIDS_ARRAY[@]}"; do
    FOUND=false
    for java_pid in "${JAVA_PIDS_ARRAY[@]}"; do
        if [ "$pid" = "$java_pid" ]; then
            FOUND=true
            break
        fi
    done
    
    if [ "$FOUND" = true ]; then
        echo "✓ PID $pid 在ss -antlp的java进程中找到，进程正常"
    else
        echo "✗ PID $pid 在ss -antlp的java进程中未找到，标记为需要杀死"
        PIDS_TO_KILL+=($pid)
    fi
done

# 显示结果但不实际杀死进程（安全起见）
if [ ${#PIDS_TO_KILL[@]} -eq 0 ]; then
    echo "所有acs_server.jar进程都正常运行，无需操作"
else
    echo "发现 ${#PIDS_TO_KILL[@]} 个异常进程，需要杀死: ${PIDS_TO_KILL[*]}"
    #echo "*** 注意：当前为调试模式，不会实际杀死进程 ***"
    
    #取消注释下面的代码来实际杀死进程
    for pid in "${PIDS_TO_KILL[@]}"; do
         echo "杀死进程 $pid"
         kill -9 $pid
         if [ $? -eq 0 ]; then
             echo "进程 $pid 已被成功杀死"
         else
             echo "杀死进程 $pid 失败"
         fi
     done
fi